<template>
  <div class="bind-we-chart" v-loading.fullscreen.lock="loading">
    <template v-if="codeImg!==null">
      <div style="text-align:center">
        <img :src="codeImg">
      </div>
      <div class="code-text">
        <div>请使用微信扫描二维码绑定账号</div>
        <div style="color:#ff0000">注:该二维码5分钟内有效</div>
      </div>
    </template>
  </div>
</template>

<script>
  import QRCode from 'qrcode';
  import GlobalData from 'utils/globalData';

  import WeChartApi from 'services/weChartApi';

  export default {
    props: {
      user: {
        type: Object,
        required: true
      }
    },

    data() {
      return {
        loading: false,
        codeImg: null
      };
    },

    created() {
      this.createCode();
    },

    methods: {
      createCode() {
        this.loading = true;
        WeChartApi.getBindCode().then(code => {
          let url = `${GlobalData.bindAccountUrl}?code=${code}&userId=${this.user.userId}`;
          return QRCode.toDataURL(url, {
            margin: 0,
            errorCorrectionLevel: 'L',
            width: 200
          }).then(url => {
            this.codeImg = url;
            this.loading = false;
            this.$emit('create-code', code);
          });
        }).catch(() => {
          this.loading = false;
        });
      }
    }
  };

</script>

<style lang="scss" scoped>
  .bind-we-chart {
    padding: 0 10px 10px;

    .code-text {
      margin: auto;
      margin-top: 5px;
      font-size: 13px;
      line-height: 20px;
      text-align: center;
    }
  }

</style>
